<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

class igcategoriesModelIgcategories extends igbaseModel
{
	protected $context = 'igcategories';
	protected $tablename = 'igallery';
	protected $filterOrderDefault = 'ordering';
	
	function __construct($task)
	{
		parent::__construct();
    }
    
    function getData()
	{
		global $mainframe;
		
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$categories = $this->_getList($query);
		    $children = array();
    
    		foreach ($categories as $v )
    		{
    			$pt = $v->parent;
    			$list = @$children[$pt] ? $children[$pt] : array();
    			array_push($list, $v);
    			$children[$pt] = $list;
    		}
    
    		$list = JHTML::_('menu.treerecurse',  0, '', array(), $children, max( 0, 9 ) );
    		
    		$search	= $mainframe->getUserStateFromRequest( 'igcategories.search', 'search', '', 'string' );
    		if(strpos($search, '"') !== false)
    		{
				$search = str_replace(array('=', '<'), '', $search);
			}
			$search = JString::strtolower($search);
			
			if($search)
			{
				$query = 'SELECT id FROM #__igallery WHERE '.
				'LOWER(name) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
				$this->_db->setQuery( $query );
				$search_rows = $this->_db->loadResultArray();
				
				$list1 = array();
	
				foreach ($search_rows as $sid )
				{
					foreach ($list as $item)
					{
						if ($item->id == $sid) 
						{
							$list1[] = $item;
						}
					}
				}
				
				$list = $list1;
			}
			
			$filter_state = $mainframe->getUserStateFromRequest( 'igcategories.filter_state', 'filter_state', '', 'word');
			
			if($filter_state)
			{
				$publishedWhere = '';
				if($filter_state == 'P')
				{
					$publishedWhere = 'published = 1';
				}
				else if($filter_state == 'U' )
				{
					$publishedWhere = 'published = 0';
				}
				
				$query = 'SELECT id FROM #__igallery WHERE '.$publishedWhere;
				$this->_db->setQuery($query);
				$published_rows = $this->_db->loadResultArray();
				
				$list2 = array();
	
				foreach ($published_rows as $sid )
				{
					foreach ($list as $item)
					{
						if ($item->id == $sid) 
						{
							$list2[] = $item;
						}
					}
				}
				
				$list = $list2;
			}
    		
    		$orderedList = array_values($list);
            $limit = $this->getState('limit') == 0 ? 9999 : $this->getState('limit');
            $this->_data = array_slice( $orderedList, $this->getState('limitstart'), $limit );
		}

		return $this->_data;
	}
	
	function _buildQuery()
	{
		$orderby	= $this->_buildContentOrderBy();
        $query = 'SELECT * from #__igallery ' . $orderby;
        return $query;
	}
	
	function getDataFrontend()
	{
		$query = 'SELECT * from #__igallery ORDER BY ordering';
		
		$this->_categories = $this->_getList($query);
		
		$count = count($this->_categories);
		
		for($i=0; $i<$count; $i++ )
		{
			if( !$this->authenticate('acl_cat_view', $this->_categories[$i]->id) )
			{
				unset($this->_categories[$i]);
			}
		}
		$this->_categories = array_values($this->_categories);
		
		return $this->_categories;
	}
	
	function save($data)
	{
		$row =& $this->getTable('igallery');
		$user =& JFactory::getUser();
		$configArray =& JComponentHelper::getParams('com_igallery');
		
        $row->id = (int)$this->_id;
		if (!$row->bind($data)) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if(!$row->id) 
		{
		    $firstLast = $configArray->get('new_cat_ordering', 'last');
		    $row->ordering = $firstLast == 'first' ? 0 : $row->getNextOrder('parent = '.(int)$row->parent);
		}
		
		$row->user = empty($row->user) ? $user->id : $row->user;
		$row->menu_description = JRequest::getVar( 'menu_description', '', 'post', 'string', JREQUEST_ALLOWHTML );
		$row->gallery_description = JRequest::getVar( 'gallery_description', '', 'post', 'string', JREQUEST_ALLOWHTML );

		
		$row->alias = empty($row->alias) ? JFilterOutput::stringURLSafe($row->name) : JFilterOutput::stringURLSafe($row->alias);
		
		$row->profile = empty($row->profile) ? $configArray->get('default_profile', 1) : $row->profile;
		$row->parent = $row->parent == null ? $configArray->get('default_parent', 0) : $row->parent;
		$row->name = empty($row->name) ? '____' : $row->name;
		$row->moderate = $configArray->get('moderate_cat', 0) == 0 || IG_BACKEND == true ? 1 : 0;
		
		
		if($data['remove_menu_image'] == 1)
		{
		    $query = 'SELECT menu_image_filename FROM #__igallery WHERE id = '.(int)$this->_id;
            $this->_db->setQuery($query);
            $this->_category = $this->_db->loadObject();
		    
		    $query = 'SELECT menu_image_filename FROM #__igallery WHERE menu_image_filename = '.$this->_db->Quote($this->_category->menu_image_filename);
    		$this->_db->setQuery($query);
    		$this->_db->query();
    		$numRows = $this->_db->getNumRows();
    		$deleteImg = $numRows > 1 ? false: true;
    		
    		if($deleteImg)
    		{
    	       igFileHelper::deleteImage($this->_category->menu_image_filename, $deleteImg);
    		}
    	    
    	    $row->menu_image_filename =  '';
		}
		
		if(!$row->store()) 
		{
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}
		
		if(trim(str_replace('-','',$row->alias)) == '' )
		{
			$row->alias = 'category-'.(int)$row->id;
			if(!$row->store()) 
			{
				$this->setError( $this->_db->getErrorMsg() );
				return false;
			}
		}
		
		$query = 'SELECT alias from #__igallery where alias = "'.$this->_db->getEscaped($row->alias).'"';
		$this->_db->setQuery($query);
        $rows = $this->_db->loadObjectList();
        
        if( count($rows) > 1)
        {
        	$row->alias = $row->alias.'-'.(int)$row->id;
			if(!$row->store()) 
			{
				$this->setError( $this->_db->getErrorMsg() );
				return false;
			}
        }
		
		
		if($firstLast == 'first')
	    {
	       $row->reorder('parent = '.(int)$row->parent);
	    }
	    
	    if(IG_BACKEND == false)
	    {
			if($configArray->get('notify_new_category', 0) == 1)
			{
				$this->notify('category', $row->id);
			}
	    }

		return true;
	}
	
	function remove()
	{
	    $query = 'SELECT * FROM #__igallery WHERE id = '.(int)$this->_id;
        $this->_db->setQuery($query);
        $this->_category = $this->_db->loadObject();
        
        if( strlen($this->_category->menu_image_filename) > 2 )
        {
            $query = 'SELECT menu_image_filename FROM #__igallery WHERE menu_image_filename = '.$this->_db->Quote($this->_category->menu_image_filename);
    		$this->_db->setQuery($query);
    		$this->_db->query();
    		$numRows = $this->_db->getNumRows();
    		$deleteOrig = $numRows > 1 ? false: true;
    		
            igFileHelper::deleteImage($this->_category->menu_image_filename, $deleteOrig);
        }
        
        $query = 'SELECT id, filename FROM #__igallery_img WHERE gallery_id = '.(int)$this->_id;
        $this->_db->setQuery($query);
        $this->_photoList = $this->_db->loadObjectList();
        
        for($i=0; $i<count($this->_photoList); $i++)
		{
		    $photo =& $this->_photoList[$i];
		    
		    $query = 'SELECT filename FROM #__igallery_img WHERE filename = '.$this->_db->Quote($photo->filename);
    		$this->_db->setQuery($query);
    		$this->_db->query();
    		$numRows = $this->_db->getNumRows();
    		$deleteOrig = $numRows > 1 ? false: true;
    		
    	    igFileHelper::deleteImage($photo->filename, $deleteOrig);
		    
    		//delete the comments for this photo
    		$query = 'DELETE FROM #__igallery_comments WHERE img_id = '.(int)$photo->id;
    		$this->_db->setQuery($query);
    		if(!$this->_db->query())
    		{
    			$this->setError($this->_db->getErrorMsg());
    			return false;
    		}
            
    		
    		//delete the ratings for this photo
    		$query = 'DELETE FROM #__igallery_rating WHERE img_id = '.(int)$photo->id;
    		$this->_db->setQuery($query);
    
    		if(!$this->_db->query())
    		{
    			$this->setError($this->_db->getErrorMsg());
    			return false;
    		}
            
    		//delete the photo row
    		$query = 'DELETE FROM #__igallery_img WHERE id = '.(int)$photo->id;
    		$this->_db->setQuery($query);
    		if(!$this->_db->query())
    		{
    			$this->setError($this->_db->getErrorMsg());
    			return false;
    		}
    		
		}
	    
		//delete the category row
		$query = 'DELETE FROM #__igallery WHERE id = '.(int)$this->_id;
		$this->_db->setQuery($query);
		if(!$this->_db->query())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		//put any child categories in the top level
		$query = 'UPDATE #__igallery SET parent = 0 WHERE parent = '.(int)$this->_id;
		$this->_db->setQuery($query);
		if(!$this->_db->query())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		$row =& $this->getTable('igallery');
    	$row->reorder('parent = '.(int)$this->_category->parent);
		
		return true;
	}
	
	function copy($post)
	{
	    $row =& $this->getTable('igallery');
	    
	    //load the category to copy
        $row->load($this->_id);
        
        //set some of the new values
        $row->id = null;
        $row->ordering = $row->getNextOrder('parent = '.(int)$row->parent);
        $row->name = JText::_('COPY OF').' '.$row->name;
        $row->alias = JFilterOutput::stringURLSafe($row->name);
        
        //save the new category
        if (!$row->store())
    	{
    		JError::raise(2, 500, $row->getError());
    		return false;
    	}
    	
    	$catId = $this->_db->insertid();
    	
    	//get all the photo rows of the old category
    	$query = 'SELECT * FROM #__igallery_img WHERE gallery_id = '.(int)$this->_id;
		$photos = $this->_getList($query);
		
		$row =& $this->getTable('igallery_img');
		
		for($i=0; $i<count($photos); $i++)
		{
		    $photo =& $photos[$i];
		    
            $row->load($photo->id);
            $row->id = null;
            $row->gallery_id = $catId;
		   
            if(!$row->store())
            {
               JError::raise(2, 500, $row->getError());
               return false;
            }
		}
		
		return true;
	}
	
	function move($direction)
	{
		$row =& $this->getTable('igallery');
		if (!$row->load($this->_id)) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->move( $direction, ' parent = '.(int) $row->parent )) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		$row->reorder('parent = '.(int)$row->parent);

		return true;
	}

	function saveorder()
	{
	    $cid 	= JRequest::getVar( 'cid', array(), '', 'array' );
		$order 	= JRequest::getVar( 'order', array(), '', 'array' );
		JArrayHelper::toInteger($cid);
		JArrayHelper::toInteger($order);
		
		$row =& $this->getTable('igallery');
		$groupings = array();

		for( $i=0; $i < count($cid); $i++ )
		{
			$row->load( (int) $cid[$i] );
			$groupings[] = $row->parent;

			if ($row->ordering != $order[$i])
			{
				$row->ordering = $order[$i];
				if (!$row->store()) 
				{
					$this->setError($this->_db->getErrorMsg());
					return false;
				}
			}
		}

		$groupings = array_unique( $groupings );
		foreach ($groupings as $group)
		{
			$row->reorder('parent = '.(int) $group);
		}

		return true;
	}
}	